package com.gdk.ksoft.assembly.utils;

import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.gdk.ksoft.data.common.ConstantData;
import com.gdk.ksoft.data.common.SystemData;
import com.gdk.ksoft.data.common.constants.TaskConstant;
import com.gdk.ksoft.data.entry.datas.BaseResultModel;
import com.gdk.ksoft.data.entry.tables.CustomerLatLngTable;
import com.gdk.ksoft.data.entry.tables.CustomerTable;
import com.gdk.ksoft.data.entry.tables.DeliverGoodsTable;
import com.gdk.ksoft.data.entry.tables.SaleGoodsTable;
import com.gdk.ksoft.data.entry.tables.SaleManRouteTable;
import com.gdk.ksoft.data.entry.tables.SaleStatisticsTable;
import com.gdk.ksoft.data.entry.tables.SaleTable;
import com.gdk.ksoft.ui.MainActivity;
import com.gdk.ksoft.assembly.receiver.UploadNotifyReciever;
import com.gdk.ksoft.assembly.utils.extensions.FormatUtils;
import com.gdk.ksoft.assembly.utils.extensions.MD5Utils;
import com.gdk.ksoft.assembly.utils.system.FileUtils;
import com.gdk.ksoft.assembly.utils.system.NetworkUtils;
import com.google.gson.Gson;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest;

import java.io.InputStream;
import java.util.List;

/**
 * Created by hel on 2015-01-09.
 * 后台任务操作类
 */
public class TaskUtils {


    /**
     * 存储经纬度数据到本地
     * @param dbUtils
     * @throws Exception
     */
    public synchronized static void saveLatlngToLocation(final DbUtils dbUtils)throws Exception{
        dbUtils.delete(SaleManRouteTable.class, WhereBuilder.b("djbz", "=", "1"));//在上传之前，先清理一次数据
        if (SystemData.currentLocation != null) {//如果当前的经纬度不为空
            SaleManRouteTable route = new SaleManRouteTable();
            route.jwd = SystemData.currentLocation.getLatitude() + "," + SystemData.currentLocation.getLongitude();
            route.djbz = 0;//单机标识=0，未上传
            route.xgsj = FormatUtils.standardDatetime(new java.util.Date(), "yyyy-MM-dd HH:mm:ss");//记录数据的时间
            route.ywy_id = SystemData.SaleManID;//业务员ID
            dbUtils.save(route);
        }
    }

    /**
     * 上传经纬度等数据(自动上传的)
     * @param dbUtils
     * @throws Exception
     */
    public synchronized static void uploadLatlng(final Context context,final DbUtils dbUtils)throws Exception{
        if(NetworkUtils.isNetAvailable(context)){//如果网络可以使用
            final List<SaleManRouteTable> routelst = dbUtils.findAll(Selector.from(SaleManRouteTable.class).where("djbz","=",0));
            if(routelst!=null && routelst.size()>0){
                String value = new Gson().toJson(routelst);//把路径数据转换为JSON字符串
                HttpUtils httpUtils = new HttpUtils(ConstantData.NETWORK_CONNECT_TIME_OUT)
                        .configSoTimeout(ConstantData.NETWORK_READ_TIME_OUT);
                String methodName = "Cx_UpYwyBfgj";
                String messageBody = "{\"Sjch\":\"" + SystemData.PhoneIMEI+"\",\"Data\":{\"bfgjs\":"+ value + "}}";
                System.out.println("-----> 正在上传业务员路径数据："+messageBody);
                RequestParams params = new RequestParams("UTF-8");
                params.addBodyParameter("Method", methodName);
                params.addBodyParameter("Digest", MD5Utils.getMd5(methodName + messageBody + "19491001"));
                params.addBodyParameter("MessageBody", messageBody);
                InputStream is = httpUtils.sendSync(HttpRequest.HttpMethod.POST,SystemData.BASE_URL,params);
                if(is!=null){
                    String resultString = FileUtils.stream2string(is, "utf-8");
                    System.out.println("-----> 业务员轨迹上传结果：" + resultString);
                    //数据上传成功
                    BaseResultModel resultModel = new Gson().fromJson(resultString,BaseResultModel.class);
                    if(resultModel.Result.equals("0000")){//上传成功
                        try {
                            dbUtils.deleteAll(routelst);//删除所有已经上传的数据
                        }catch (Exception  e){
                            e.printStackTrace();
                        }
                    }
                }else{
                    System.out.println("网络错误，上传业务员跑单轨迹失败!");
                }
            }
        }
    }

    /**
     * 上传修改过的客户信息（自动上传的）
     */
    public synchronized static void uploadCustomerInformation(final Context context,final DbUtils dbUtils)throws Exception{
        if(NetworkUtils.isNetAvailable(context)) {
            final CustomerTable item =
                    dbUtils.findFirst(Selector.from(CustomerTable.class)
                            .where("djbz", "=", 0).and("state","=",2));
            if(item == null) return;//没有数据可以上传
            HttpUtils httpUtils = new HttpUtils(ConstantData.NETWORK_CONNECT_TIME_OUT)
                    .configSoTimeout(ConstantData.NETWORK_READ_TIME_OUT);
            String methodName = "Cx_UpdateKh";
            String messageBody = "{\"Sjch\":\"" + SystemData.PhoneIMEI + "\",\"Data\":{\"updateKh\":"+new Gson().toJson(item)+"}}";
            System.out.println("-----> 后台正在上传客户信息地址数据：" + messageBody);
            RequestParams params = new RequestParams("UTF-8");
            params.addBodyParameter("Method", methodName);
            params.addBodyParameter("Digest", MD5Utils.getMd5(methodName + messageBody + "19491001"));
            params.addBodyParameter("MessageBody", messageBody);
            InputStream is = httpUtils.sendSync(HttpRequest.HttpMethod.POST, SystemData.BASE_URL, params);
            String result = FileUtils.stream2string(is, "utf-8");
            System.out.println("----->后台上传客户信息结果："+result);
            if (!TextUtils.isEmpty(result)) {
                BaseResultModel resultModel = new Gson().fromJson(result, BaseResultModel.class);
                if (resultModel.Result.equals("0000")) {
                    item.djbz = 1;//修改单机标识
                    item.state = 0;//修改客户状态为正常状态
                    dbUtils.update(item,"djbz","state");
                }
            }else{
                System.out.println("----->后台上传客户信息失败!");
            }
        }
    }

    /**
     * 上传修改过的客户信息（手动上传的）
     */
    public synchronized static void uploadAllCustomerInformation(final Context context,final DbUtils dbUtils,
           MainActivity.OnUploadListener listener)throws Exception{
        if(NetworkUtils.isNetAvailable(context)) {
            MainActivity.ProgressValue progress = new MainActivity.ProgressValue();
            List<CustomerTable> customerlist = dbUtils.findAll(Selector.from(CustomerTable.class)
                    .where("djbz", "=", 0).and("state","=",2));
            progress.total = customerlist == null?0:customerlist.size();
            if(progress.total == 0) return;//没有数据可上传
            for(int i=0;i<progress.total;i++) {
                try{
                    final CustomerTable item = customerlist.get(i);
                    if (item == null) return;//没有数据可以上传
                    HttpUtils httpUtils = new HttpUtils(ConstantData.NETWORK_CONNECT_TIME_OUT)
                            .configSoTimeout(ConstantData.NETWORK_READ_TIME_OUT);
                    String methodName = "Cx_UpdateKh";
                    String messageBody = "{\"Sjch\":\"" + SystemData.PhoneIMEI + "\",\"Data\":{\"updateKh\":" + new Gson().toJson(item) + "}}";
                    System.out.println("-----> 后台正在上传客户信息地址数据：" + messageBody);
                    RequestParams params = new RequestParams("UTF-8");
                    params.addBodyParameter("Method", methodName);
                    params.addBodyParameter("Digest", MD5Utils.getMd5(methodName + messageBody + "19491001"));
                    params.addBodyParameter("MessageBody", messageBody);
                    InputStream is = httpUtils.sendSync(HttpRequest.HttpMethod.POST, SystemData.BASE_URL, params);
                    String result = FileUtils.stream2string(is, "utf-8");
                    System.out.println("----->后台上传客户信息结果：" + result);
                    if (!TextUtils.isEmpty(result)) {
                        BaseResultModel resultModel = new Gson().fromJson(result, BaseResultModel.class);
                        if (resultModel.Result.equals("0000")) {
                            item.djbz = 1;//修改单机标识
                            item.state = 0;//修改客户状态为正常状态
                            dbUtils.update(item, "djbz", "state");
                        }
                        progress.executedNum++;//已经上传的数量
                        if(listener!=null)listener.onExecuteUpload(progress);
                    } else {
                        System.out.println("----->后台上传客户信息失败!");
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 上传客户送货地址,要求收货地址的本地ID必须为0，否则该收货地址属于新增客户的收货地址（自动上传的）
     */
    public synchronized static void uploadDeliverAddress(final Context context,final DbUtils dbUtils)throws Exception{
        if(NetworkUtils.isNetAvailable(context)) {
            final DeliverGoodsTable item = dbUtils.findFirst(Selector.from(DeliverGoodsTable.class).where("djbz", "=", 0));
            if(item == null) return;//没有数据可以上传
            HttpUtils httpUtils = new HttpUtils(ConstantData.NETWORK_CONNECT_TIME_OUT)
                    .configSoTimeout(ConstantData.NETWORK_READ_TIME_OUT);
            String methodName = "Cx_UpKhShdz";
            String messageBody = "{\"Sjch\":\"" + SystemData.PhoneIMEI + "\",\"Data\":{\"upShdz\":"+new Gson().toJson(item)+"}}";
            System.out.println("-----> 正在上传客户收货地址数据：" + messageBody);
            RequestParams params = new RequestParams("UTF-8");
            params.addBodyParameter("Method", methodName);
            params.addBodyParameter("Digest", MD5Utils.getMd5(methodName + messageBody + "19491001"));
            params.addBodyParameter("MessageBody", messageBody);
            InputStream is = httpUtils.sendSync(HttpRequest.HttpMethod.POST, SystemData.BASE_URL, params);
            String result = FileUtils.stream2string(is, "utf-8");
            System.out.println("----->上传客户收货地址结果："+result);
            if (!TextUtils.isEmpty(result)) {
                BaseResultModel resultModel = new Gson().fromJson(result, BaseResultModel.class);
                if (resultModel.Result.equals("0000")) {
                    item.djbz = 1;//修改单机标识
                    if(item.id <= 0) {//该收货地址是新增的
                        item.id = Integer.parseInt(resultModel.Data);//返回的自增长ID
                        dbUtils.update(item, "djbz", "id");//更新数据库参数
                    }else{
                        dbUtils.update(item, "djbz");//更新数据库参数
                    }
                }else{
                    System.out.println(resultModel.Message+"，上传客户收货地址失败!");
                }
            }
        }else{
            System.out.println("网络错误，上传客户收货地址失败!");
        }
    }

    /**
     * 上传客户收货地址,要求收货地址的本地ID必须为0，否则该收货地址属于新增客户的收货地址(手动上传的)
     */
    public synchronized static void uploadAllDeliverAddress(final Context context,final DbUtils dbUtils,
           MainActivity.OnUploadListener listener)throws Exception{
        if(NetworkUtils.isNetAvailable(context)) {
            List<DeliverGoodsTable> deliverlist = dbUtils.findAll(Selector.from(DeliverGoodsTable.class).where("djbz", "=", 0));
            MainActivity.ProgressValue progressValue = new MainActivity.ProgressValue();
            progressValue.total = deliverlist == null ? 0 : deliverlist.size();
            if (progressValue.total == 0) return;//无数据可上传
            for (int i = 0; i < progressValue.total; i++) {
                try {
                    final DeliverGoodsTable item = deliverlist.get(i);
                    if (item == null) return;//没有数据可以上传
                    HttpUtils httpUtils = new HttpUtils(ConstantData.NETWORK_CONNECT_TIME_OUT)
                            .configSoTimeout(ConstantData.NETWORK_READ_TIME_OUT);
                    String methodName = "Cx_UpKhShdz";
                    String messageBody = "{\"Sjch\":\"" + SystemData.PhoneIMEI + "\",\"Data\":{\"upShdz\":" + new Gson().toJson(item) + "}}";
                    System.out.println("-----> 正在上传客户收货地址数据：" + messageBody);
                    RequestParams params = new RequestParams("UTF-8");
                    params.addBodyParameter("Method", methodName);
                    params.addBodyParameter("Digest", MD5Utils.getMd5(methodName + messageBody + "19491001"));
                    params.addBodyParameter("MessageBody", messageBody);
                    InputStream is = httpUtils.sendSync(HttpRequest.HttpMethod.POST, SystemData.BASE_URL, params);
                    String result = FileUtils.stream2string(is, "utf-8");
                    System.out.println("----->上传客户收货地址结果：" + result);
                    if (!TextUtils.isEmpty(result)) {
                        BaseResultModel resultModel = new Gson().fromJson(result, BaseResultModel.class);
                        if (resultModel.Result.equals("0000")) {
                            item.djbz = 1;//修改单机标识
                            if (item.id <= 0) {//该收货地址是新增的
                                item.id = Integer.parseInt(resultModel.Data);//返回的自增长ID
                                dbUtils.update(item, "djbz", "id");//更新数据库参数
                            } else {
                                dbUtils.update(item, "djbz");//更新数据库参数
                            }
                            progressValue.executedNum++;//已经处理掉的数据
                            if(listener!=null) listener.onExecuteUpload(progressValue);
                        } else {
                            System.out.println(resultModel.Message + "，上传客户收货地址失败!");
                        }
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 上传送货地址经纬度地址到服务器（自动上传的）
     */

    public synchronized static void uploadDeliverGoodsAddress(final Context context,final DbUtils dbUtils) throws Exception {
        final CustomerLatLngTable lntlng = dbUtils.findFirst(Selector.from(CustomerLatLngTable.class).where("djbz", "=", "0"));
        if (lntlng != null && NetworkUtils.isNetAvailable(context)) {//如果数据不为空，传递数据
            RequestParams params = new RequestParams("UTF-8");
            String methodName = "Cx_UpdateShdzJwd";
            String messageBody = "{\"Sjch\":\"" + SystemData.PhoneIMEI + "\",\"Data\":{\"shdzId\":\""
                    + lntlng.shdz_id + "\",\"jwd\":\"" + lntlng.latlng + "\"}}";
            System.out.println("-----> 传递客户收货地址经纬度数据是：" + messageBody);
            params.addBodyParameter("Method", methodName);
            params.addBodyParameter("Digest", MD5Utils.getMd5(methodName + messageBody + "19491001"));
            params.addBodyParameter("MessageBody", messageBody);
            InputStream inputStream = new HttpUtils(ConstantData.NETWORK_CONNECT_TIME_OUT)
                    .configSoTimeout(ConstantData.NETWORK_READ_TIME_OUT)
                    .sendSync(HttpRequest.HttpMethod.POST, SystemData.BASE_URL, params);
            if(inputStream!=null){
                String resultString = FileUtils.stream2string(inputStream,"utf-8");
                System.out.println("-----> 传递客户收货地址经纬度返回数据是：" + resultString);
                BaseResultModel resultModel = new Gson().fromJson(resultString, BaseResultModel.class);
                if (resultModel.Result.equals("0000")) {
                    SQLiteDatabase database = dbUtils.getDatabase();
                    database.beginTransaction();
                    try {
                        dbUtils.delete(lntlng);
                        lntlng.djbz = 1;//设置为网络标识
                        dbUtils.update(lntlng, "djbz");
                        database.setTransactionSuccessful();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }finally {
                        database.endTransaction();
                    }
                }else{
                    System.out.println("----->"+resultModel.Message + "，上传客户收货地址经纬度失败!");
                }
            }else {
                System.out.println("----->网络错误，传递收货地址数据经纬度失败!");
            }
        }

    }

    /**
     * 上传所有送货地址经纬度地址到服务器（手动上传的）
     */
    public synchronized static void uploadAllDeliverGoodsAddress(final Context context,final DbUtils dbUtils,
          MainActivity.OnUploadListener listener) throws Exception {
        MainActivity.ProgressValue progressValue = new MainActivity.ProgressValue();
        if(!NetworkUtils.isNetAvailable(context)){
            if(listener!=null) listener.onExecuteUpload(progressValue);
            return ;//网络不可用
        }
        final List<CustomerLatLngTable> lntlngs = dbUtils.findAll(Selector.from(CustomerLatLngTable.class).where("djbz", "=", "0"));
        int dataLen = lntlngs == null?0:lntlngs.size();//获取数据的总数
        progressValue.total = dataLen;//设置数据长度
        for(int i=0;(lntlngs!=null&&i<lntlngs.size());i++){
            try{
                CustomerLatLngTable lntlng = lntlngs.get(i);//获取当前送货地址的经纬度
                RequestParams params = new RequestParams("UTF-8");
                String methodName = "Cx_UpdateShdzJwd";
                String messageBody = "{\"Sjch\":\"" + SystemData.PhoneIMEI + "\",\"Data\":{\"shdzId\":\""
                        + lntlng.shdz_id + "\",\"jwd\":\"" + lntlng.latlng + "\"}}";
                System.out.println("-----> 传递客户收货地址经纬度数据是：" + messageBody);
                params.addBodyParameter("Method", methodName);
                params.addBodyParameter("Digest", MD5Utils.getMd5(methodName + messageBody + "19491001"));
                params.addBodyParameter("MessageBody", messageBody);
                InputStream inputStream = new HttpUtils(ConstantData.NETWORK_CONNECT_TIME_OUT)
                        .configSoTimeout(ConstantData.NETWORK_READ_TIME_OUT)
                        .sendSync(HttpRequest.HttpMethod.POST, SystemData.BASE_URL, params);
                if (inputStream != null) {
                    String resultString = FileUtils.stream2string(inputStream, "utf-8");
                    System.out.println("-----> 传递客户收货地址经纬度返回数据是：" + resultString);
                    BaseResultModel resultModel = new Gson().fromJson(resultString, BaseResultModel.class);
                    if (resultModel.Result.equals("0000")) {
                        SQLiteDatabase database = dbUtils.getDatabase();
                        database.beginTransaction();
                        try {
                            dbUtils.delete(lntlng);
                            lntlng.djbz = 1;//设置为网络标识
                            dbUtils.update(lntlng, "djbz");
                            database.setTransactionSuccessful();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        database.endTransaction();
                        progressValue.executedNum++;//已经上传的数量
                        if(listener!=null) listener.onExecuteUpload(progressValue);
                    } else {
                        System.out.println("----->" + resultModel.Message + "，上传客户收货地址经纬度失败!");
                    }
                } else {
                    System.out.println("----->网络错误，传递收货地址数据经纬度失败!");
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }


    /**
     * 从服务器请求单据号（自动获取）
     *
     * @param isNormalOrder true-销售单据号，false-退货单据号
     */
    public synchronized static void requestOrderNo(final Context context,final DbUtils dbUtils, final boolean isNormalOrder) throws Exception {
        if (context == null || !NetworkUtils.isNetAvailable(context)) return;//网络不可用，不进行单号请求
        final SaleTable saleTable = dbUtils.findFirst(Selector.from(SaleTable.class).where("substr(djh,1,3)", "=", isNormalOrder ? "NOB" : "NOS"));
        if (saleTable == null) return;
        String orderNo = getOrderNoFromWeb(isNormalOrder);//从网络上获取单据号
        if(TextUtils.isEmpty(orderNo) || orderNo.startsWith("NO")) return;//请求单据号失败
        SQLiteDatabase database = dbUtils.getDatabase();
        boolean isTransaction = false;//是否执行了事务处理
        try {
            final String orignalNo = saleTable.djh;//保存原来的单据号
            List<SaleGoodsTable> saleGoodsTableList = dbUtils.findAll(Selector.from(SaleGoodsTable.class)
                    .where("xsd_id", "=", orignalNo));
            List<SaleStatisticsTable> saleStatisticsTableList = null;
            if (saleTable.ddlx == 0) {//如果是销售单，标识是0  ---  修改结算表数据
                saleStatisticsTableList = dbUtils.findAll(Selector.from(SaleStatisticsTable.class).where("djh", "=", orignalNo));
            }
            database.beginTransaction();
            isTransaction = true;
            saleTable.djh = orderNo;//重新赋值单据号
            dbUtils.update(saleTable, "djh");//重新保存数据
            if (saleGoodsTableList != null && saleGoodsTableList.size() > 0) {
                for (SaleGoodsTable item : saleGoodsTableList) {
                    item.xsd_id = orderNo;
                    dbUtils.update(item, "xsd_id");//同步单据信息，xsd_id作为了外键值
                }
            }
            if (saleStatisticsTableList != null && saleStatisticsTableList.size() > 0) {//如果结算数据存在，则更新结算表
                for (SaleStatisticsTable item : saleStatisticsTableList) {
                    item.djh = orderNo;
                    item.xsd_id = orderNo;
                    dbUtils.update(item, "djh","xsd_id");//同步单据信息，xsd_id作为了外键值
                }
            }
            if(isTransaction) {
                database.setTransactionSuccessful();
            }
            System.out.println("----->请求单据号数据成功！");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("----->请求单据号数据失败："+e.getMessage());
        }finally {
            if (isTransaction) {
                database.endTransaction();
            }
        }
    }

    /**
     * 上传销售单数据到服务器（自动上传）
     */
    public synchronized static void uploadSaleOrders(final Context context,final DbUtils dbUtils) throws Exception{
        if (context == null || !NetworkUtils.isNetAvailable(context)) return;
        final SaleTable saleTable = dbUtils.findFirst(Selector.from(SaleTable.class)
                .where("substr(djh,1,2)","<>","NO").and("djbz","=",0));
        if(saleTable == null) return;//未找到可上传的销售单
        final List<SaleGoodsTable> saleGoodsTableList = dbUtils.findAll(Selector.from(SaleGoodsTable.class)
                .where("xsd_id","=",saleTable.djh).and("djbz","=",0));
        if(saleGoodsTableList!=null && saleGoodsTableList.size()>0)
            uploadSingleSale(dbUtils,saleTable,saleGoodsTableList);//上传单个销售单数据到服务器
    }

    /**
     * 上传单个销售单数据到服务器（自动+手动）
     * @throws Exception
     */
    public synchronized static boolean uploadSingleSale(final DbUtils dbUtils,final SaleTable saleTable,final List<SaleGoodsTable> saleGoodsTableList){
        boolean isUploadOk = true;//是否上传成功
        String goodsStr = new Gson().toJson(saleGoodsTableList);//把销售单下面对应的商品转化为JSON字符串
        RequestParams params = new RequestParams("UTF-8");
        String methodName = "Cx_UpXsd";
        String messageBody = "{\"Sjch\":\"" + SystemData.PhoneIMEI + "\",\"Data\":{\"xsd\":"+new Gson().toJson(saleTable)+",\"xsdsps\":"+goodsStr+"}}";
        System.out.println("-----> 上传销售单数据是：" + messageBody);
        params.addBodyParameter("Method", methodName);
        params.addBodyParameter("Digest", MD5Utils.getMd5(methodName + messageBody + "19491001"));
        params.addBodyParameter("MessageBody", messageBody);
        try {
            InputStream inputStream = new HttpUtils(ConstantData.NETWORK_CONNECT_TIME_OUT)
                    .configSoTimeout(ConstantData.NETWORK_READ_TIME_OUT)
                    .sendSync(HttpRequest.HttpMethod.POST, SystemData.BASE_URL, params);
            if (inputStream != null) {
                String resultString = FileUtils.stream2string(inputStream, "utf-8");
                System.out.println("-----> 上传销售单返回数据结果是：" + resultString);
                BaseResultModel resultModel = new Gson().fromJson(resultString, BaseResultModel.class);
                if (resultModel.Result.equals("0000")) {
                    SQLiteDatabase database = dbUtils.getDatabase();
                    try {
                        database.beginTransaction();
                        saleTable.djbz = 1;//表示已经上传
                        dbUtils.update(saleTable, "djbz");//更改销售单单机属性
                        if (saleGoodsTableList != null && saleGoodsTableList.size() > 0) {
                            for (SaleGoodsTable item : saleGoodsTableList) {
                                item.djbz = 1;//表示已经上传
                                dbUtils.update(item, "djbz");//更改销售单商品单机属性
                            }
                        }
                        database.setTransactionSuccessful();
                        System.out.println("-----> 上传销售单成功!");
                    } catch (Exception e) {
                        isUploadOk = false;
                        e.printStackTrace();
                    } finally {
                        database.endTransaction();
                    }
                } else {
                    isUploadOk = false;//上传失败
                    System.out.println("------>" + resultModel.Message + "， 上传销售单失败!");
                }
            } else {
                isUploadOk = false;
                System.out.println("-----> 网络错误，上传销售单失败!");
            }
        }catch (Exception e){
            isUploadOk = false;
            e.printStackTrace();
        }
        return isUploadOk;
    }

    /**
     * 手动上传所有【销售单、订单】数据（手动上传）
     * @return true - 完全上传成功  false - 操作失败
     * @throws Exception
     */
    public synchronized static TaskConstant handleUploadAllOrders(final DbUtils dbUtils,MainActivity.OnUploadListener listener)throws Exception{
        List<SaleTable> salelist = dbUtils.findAll(Selector.from(SaleTable.class).where("djbz", "=", 0));
        MainActivity.ProgressValue progress = new MainActivity.ProgressValue();
        if(salelist == null || salelist.size()<=0){
            if(listener!=null) listener.onExecuteUpload(progress);
            return TaskConstant.TASK_NONE;//没有可上传的数据
        }
        int count = salelist.size(),okCount = 0;//如果有数据，则统计其数量
        progress.total = count;//记录当前单据的总数
        for(int i=0;i<count;i++){
            try {
                SaleTable item = salelist.get(i);
                final String originOrderNo = item.djh;//获取以前的单据号
                List<SaleGoodsTable> saleGoodsTableList = null;//要上传的单据商品
                if (originOrderNo.startsWith("NO")) {//该单据并未申请网络单据号
                    SQLiteDatabase database = dbUtils.getDatabase();//获取数据库对象
                    boolean isTransaction = false;//是否执行过事务处理
                    boolean isExcuteOk = true;//是否处理成功
                    try {
                        String orderNo = getOrderNoFromWeb(originOrderNo.startsWith("NOB"));//NOB-销售单，NOS-销售退单
                        if (!TextUtils.isEmpty(orderNo)) {//如果请求单据号成功
                            saleGoodsTableList = dbUtils.findAll(Selector.from(SaleGoodsTable.class)
                                    .where("xsd_id", "=", originOrderNo));
                            List<SaleStatisticsTable> saleStatisticsTableList = null;
                            if (item.ddlx == 0) {//如果是销售单，标识是0  ---  修改结算表数据
                                saleStatisticsTableList = dbUtils.findAll(Selector.from(SaleStatisticsTable.class)
                                        .where("djh", "=", originOrderNo));
                            }
                            database.beginTransaction();//开启数据库事务
                            isTransaction = true;//标记为执行过事务处理
                            item.djh = orderNo;//设置当前请求到的单据号
                            dbUtils.update(item, "djh");
                            if (saleGoodsTableList != null && saleGoodsTableList.size() > 0) {
                                for (SaleGoodsTable goodsItem : saleGoodsTableList) {
                                    goodsItem.xsd_id = orderNo;
                                    dbUtils.update(goodsItem, "xsd_id");
                                }
                            }
                            if (saleStatisticsTableList != null && saleStatisticsTableList.size() > 0) {
                                for (SaleStatisticsTable statisticsItem : saleStatisticsTableList) {
                                    statisticsItem.djh = orderNo;
                                    statisticsItem.xsd_id = orderNo;
                                    dbUtils.update(item, "djh", "xsd_id");
                                }
                            }
                            database.setTransactionSuccessful();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        isExcuteOk = false;
                        System.out.println("----->修改上传的销售单、订单数据异常!");
                    }finally{
                        if(isTransaction){
                            database.endTransaction();
                        }
                        if(!isExcuteOk){//执行结果失败，继续下一次循环
                            continue;
                        }
                    }
                }else{//查询该销售单一起的商品数据
                    saleGoodsTableList = dbUtils.findAll(Selector.from(SaleGoodsTable.class)
                            .where("xsd_id", "=", item.djh).and("djbz", "=", 0));
                }
                if(uploadSingleSale(dbUtils, item, saleGoodsTableList)) {//上传单个销售单数据到服务器
                    ++okCount;//上传成功后，数量++
                }
                progress.executedNum = okCount;//记录已经成功的数量
                if(listener!=null) listener.onExecuteUpload(progress);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return (okCount == count)?TaskConstant.TASK_SUCCED:TaskConstant.TASK_FAILED;//比较成功的数量是否等于总数
    }

    /**
     * 从网络上获取单据号
     * @param isNormalOrder  true 销售单  false 退货单
     * @return
     */
    public synchronized static String getOrderNoFromWeb(final boolean isNormalOrder)throws Exception{
        RequestParams params = new RequestParams("UTF-8");
        String methodName = isNormalOrder ? "Cx_XsdDjh" : "Cx_XstDjh";
        String messageBody = "{\"Sjch\":\"" + SystemData.PhoneIMEI + "\"}";
        System.out.println("-----> 请求单据号数据数据是：" + messageBody);
        params.addBodyParameter("Method", methodName);
        params.addBodyParameter("Digest", MD5Utils.getMd5(methodName + messageBody + "19491001"));
        params.addBodyParameter("MessageBody", messageBody);
        InputStream result = new HttpUtils(ConstantData.NETWORK_CONNECT_TIME_OUT)
                .configSoTimeout(ConstantData.NETWORK_READ_TIME_OUT)
                .sendSync(HttpRequest.HttpMethod.POST, SystemData.BASE_URL, params);
        if(result == null){
            System.out.println("网络错误，请求单据号失败!");
            return null;
        }
        String resultString = FileUtils.stream2string(result,"UTF-8");
        BaseResultModel resultModel = new Gson().fromJson(resultString, BaseResultModel.class);
        if (resultModel.Result.equals("0000")) {//请求成功的
            System.out.println("-----> 请求单据号数据结果:成功【"+resultModel.Data+"】");
            return resultModel.Data;
        }else{
            System.out.println("----->"+resultModel.Message+"请求单据号数据结果：失败!");
        }
        return null;
    }


    /**
     * 发送信息到后台，开启数据上传或者关闭数据上传
     * @param isOpenUpload
     */
    public static void sendMessageToBackgroundService(Context context,boolean isOpenUpload){
        Intent intent = new Intent(UploadNotifyReciever.ACTION);
        intent.putExtra("isOpenUpload",isOpenUpload);//发送是否开启后台上传的通知
        context.sendBroadcast(intent);
    }

}
